# -*- coding: utf-8 -*-
import json

from scrapy import Spider, Request

from zhihuuser.items import UserItem


class ZhihuSpider(Spider):
    name = 'zhihu'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['http://www.zhihu.com/']

    start_user = 'excited-vczh'
    # 用户信息列表
    user_url = "https://www.zhihu.com/api/v4/members/{url_token}?include={include}"
    user_query  = "allow_message,is_followed,is_following,is_org,is_blocking,employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics"

    # 用户关注的人列表
    followees_url = "https://www.zhihu.com/api/v4/members/{url_token}/followees?include={include}&offset={offset}&limit={limit}"
    followees_query = "data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topic"

    # 用户粉丝列表
    followers_url = "https://www.zhihu.com/api/v4/members/{url_token}/followers?include={include}&offset={offset}&limit={limit}"
    followers_query = "data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics"

    def start_requests(self):
        yield Request(url=self.user_url.format(url_token=self.start_user, include=self.user_query), callback=self.parse_user)
        yield Request(url=self.followees_url.format(url_token=self.start_user, include=self.followees_query, offset=0, limit=20), callback=self.parse_followee)
        yield Request(url=self.followers_url.format(url_token=self.start_user, include=self.followers_query, offset=0, limit=20), callback=self.parse_follower)

    def parse_user(self, response):
        result = json.loads(response.text)
        item = UserItem()
        for field in item.fields:
            if field in result.keys():
                item[field] = result.get(field)
        yield item
        yield Request(url=self.followees_url.format(url_token=result.get('url_token'), include=self.followees_query, offset=0, limit=20), callback=self.parse_followee)
        yield Request(url=self.followers_url.format(url_token=result.get('url_token'), include=self.followers_query, offset=0, limit=20), callback=self.parse_follower)

    def parse_followee(self, response):
        results = json.loads(response.text)

        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(url_token=result.get('url_token'), include=self.user_query), callback=self.parse_user)

        if 'page' in results.keys() and results.get('page').get('is_end') == False:
            next_page = results.get('page').get('next')
            yield Request(next_page, callback=self.parse_followee)

    def parse_follower(self, response):
        results = json.loads(response.text)

        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(url_token=result.get('url_token'), include=self.user_query), callback=self.parse_user)

        if 'page' in results.keys() and results.get('page').get('is_end') == False:
            next_page = results.get('page').get('next')
            yield Request(next_page, callback=self.parse_follower)